import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// create an axios instance
const service = axios.create({
	//baseURL: "https://www.youlai.tech/prod-api", //  微信线上接口地址
	//baseURL: "http://www.youlai.tech:81/prod-api", //  H5/Android/iOS 线上地址
	baseURL: "http://124.223.215.40:8088", // 本地开发环境地址
	//baseURL: "http://127.0.0.1:8088", // 本地开发环境地址
	withCredentials: true, // send cookies when cross-domain requests
	crossDomain: true,
	timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		
		const token = uni.getStorageSync('token')
		if (token) {
		    config.headers['Authorization'] ='Bearer ' +token // 让每个请求携带自定义token 请根据实际情况自行修改;
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

service.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			}
		})
	})
}


// response interceptor
service.interceptors.response.use(({config,data}) => {
	let code=data.code
	if (code === 401) {
	    //   if (!isRelogin.show) {
	    //     isRelogin.show = true;
	    //     MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
	    //       confirmButtonText: '重新登录',
	    //       cancelButtonText: '取消',
	    //       type: 'warning'
	    //     }
	    //   ).then(() => {
	    //     isRelogin.show = false;
	    //     store.dispatch('LogOut').then(() => {
	    //       location.href = '/index';
	    //     })
	    //   }).catch(() => {
	    //     isRelogin.show = false;
	    //   });
	    // }
	return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
	}
	else if (code === 500) { 
	    uni.showToast({
	        title: data.msg,
	       icon: 'none'
	    })
	}
	else{
		return data
	}
	},
	error => {
		const {code,msg} = error.response.data
		if (code === '403') { // token过期
			uni.showToast({
				title: '会话已过期，请重新登录',
				success() {
					uni.navigateTo({
						url: `/pages/login/login`,
					});
				}
			})
		}
	
     else {
			uni.showToast({
				title: msg,
				icon: 'none'
			});
			return Promise.reject(new Error(msg || 'Errors'))
		}
	}
)

export default service
